package com.wxf.exceltoword.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Range;

/**
 * 导出excel
 * @author wxf
 *
 */
public class DocUtil {
	public static void build(File tmpFile, Map<String, String> contentMap, String exportFile) throws Exception {
		FileInputStream tempFileInputStream = new FileInputStream(tmpFile);
	    HWPFDocument document = new HWPFDocument(tempFileInputStream);
	    // 读取文本内容
	    Range bodyRange = document.getRange();
	    // 替换内容
	    for (Map.Entry<String, String> entry : contentMap.entrySet()) {
	        bodyRange.replaceText("${" + entry.getKey() + "}", entry.getValue());
	    }

	    //导出到文件
	    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
	    document.write(byteArrayOutputStream);
	    OutputStream outputStream = new FileOutputStream(exportFile);
	    outputStream.write(byteArrayOutputStream.toByteArray());
	    outputStream.close();
	}
	
	public static void main(String[] args) throws Exception {
		 String tmpFile = "I:/222/docTem.doc";
		    String expFile = "I:/222/result.doc";
		    Map<String, String> datas = new HashMap<String, String>();
		    datas.put("name", "标题部份");
		    datas.put("sex", "这里是内容，测试使用POI导出到Word的内容！");
		    datas.put("city", "111");
//		    datas.put("url", "http://www.zslin.com");

		    build(new File(tmpFile), datas, expFile);
	}
	
}
